package com.cgtong.android.fragment;


import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.cgtong.android.App;
import com.cgtong.android.R;
import com.cgtong.android.activity.FeedbackActivity;
import com.cgtong.android.activity.LoginActivity;
import com.cgtong.android.activity.ModifyPwdActivity;
import com.cgtong.android.activity.MyDraftActivity;
import com.cgtong.android.activity.MyExchangeActivity;
import com.cgtong.android.activity.MyFollowsActivity;
import com.cgtong.android.activity.MyInfoActivity;
import com.cgtong.android.activity.MyMessageActivity;
import com.cgtong.android.activity.MyParticipationActivity;
import com.cgtong.android.activity.MyPublicActivity;
import com.cgtong.android.activity.MyReportsActivity;
import com.cgtong.android.activity.MySettingActivity;
import com.cgtong.android.activity.SignActivity;
import com.cgtong.android.base.BaseTitleFragment;
import com.cgtong.android.bean.MessageBean;
import com.cgtong.android.bean.UserInfoBean;
import com.cgtong.android.db.UserAccount;
import com.cgtong.android.event.GetUserEvent;
import com.cgtong.android.event.LoadUserInfoEvent;
import com.cgtong.android.http.ApiManager;
import com.cgtong.android.http.ConstantManager;
import com.cgtong.android.mvp.contract.GetMessageContract;
import com.cgtong.android.mvp.contract.GetUserContract;
import com.cgtong.android.mvp.presenter.GetMessagePresenter;
import com.cgtong.android.mvp.presenter.GetUserPresenter;
import com.cgtong.android.util.CommonUtils;
import com.cgtong.android.util.PostUtil;
import com.kingja.loadsir.callback.SuccessCallback;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.callback.SimpleCallBack;
import com.zhouyou.http.cookie.CookieManger;
import com.zhouyou.http.exception.ApiException;
import com.zhouyou.http.model.ApiResult;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by tinwai on 2017/10/17.
 */

public class MeFragment extends BaseTitleFragment implements GetUserContract.View, GetMessageContract.View {

    @BindView(R.id.tv_sign)
    TextView iv_sign;
    @BindView(R.id.tv_name)
    TextView tv_name;
    @BindView(R.id.tv_point)
    TextView tv_point;
    @BindView(R.id.iv_head)
    CircleImageView iv_head;
    @BindView(R.id.message_notice)
    View message_notice;
    @BindView(R.id.tv_lev)
    TextView mUserLev;
    @BindView(R.id.tv_exchange)
    TextView mTvExchange;
    @BindView(R.id.tv_public)
    TextView mTvPublic;


    private UserAccount account;
    private GetUserPresenter presenter;
    private GetMessagePresenter messagePresenter;

    @Override
    protected String getContentTitle() {
        return getString(R.string.bottom_menu_me);
    }

    public static MeFragment newInstance() {
        return new MeFragment();
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_me;
    }

    @Override
    public void initData() {
        presenter = new GetUserPresenter(this);
        messagePresenter = new GetMessagePresenter(this);
        UserAccount account = App.getInstance().getCurrentAccount();
        if (account != null) {
            //红包开关：0显示1隐藏
            int toggle = account.getRedEnvelopes();
            if (toggle == 1) {
                mTvExchange.setVisibility(View.GONE);
                LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) mTvPublic.getLayoutParams();
                params.setMargins(0, SizeUtils.dp2px(10), 0, 0);
                mTvPublic.setLayoutParams(params);
            } else {
                mTvExchange.setVisibility(View.VISIBLE);
                LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) mTvPublic.getLayoutParams();
                params.setMargins(0, 0, 0, 0);
                mTvPublic.setLayoutParams(params);
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        getMsgData();
    }

    private void getMsgData() {
        messagePresenter.getUnreadMsg();
    }

    @Override
    public void setDatas(List<MessageBean> list) {
        if (list != null && list.size() > 0) {
            for (MessageBean msg : list) {
                if (msg.getType() != ConstantManager.MsgType.INTER) {
                    boolean isShow = !"0".equals(msg.getMsgNum());
                    if (isShow && null != message_notice) {
                        message_notice.setVisibility(View.VISIBLE);
                        return;
                    }
                }
            }
        }
        setNullData();
    }

    @Override
    public void setNullData() {
        if (null != message_notice) {
            message_notice.setVisibility(View.GONE);
        }
    }

    /*@Override
    public void onResume() {
        super.onResume();
        if (App.getInstance().isUserLogin()) {
            presenter.getUserInfo();
        }
    }*/

    @Override
    protected void loadDataByNet() {
        PostUtil.postCallbackDelayed(loadService, SuccessCallback.class);
        account = App.getInstance().getCurrentAccount();
        setUserInfo();
        EventBus.getDefault().register(this);
    }

    private void setUserInfo() {
        if (account != null) {
            tv_name.setText(account.getName());
            if (!TextUtils.isEmpty(account.getLev())) {
                mUserLev.setText(String.format(getResources().getString(R.string.txt_me_lev), account.getLev()));
            }
            tv_point.setText("积分  " + account.getScore());
            CommonUtils.setUserAvatar(getActivity(), iv_head, account.getAvatarId());
        }
    }

    @Override
    protected void onDataReloadByNet(View v) {
    }

    @OnClick({R.id.tv_sign, R.id.iv_head, R.id.tv_follow, R.id.tv_report, R.id.tv_draft, R.id.message_layout, R.id.tv_exchange,
            R.id.tv_public, R.id.tv_advise, R.id.tv_setting, R.id.tv_logout, R.id.tv_partake, R.id.tv_pwd})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_sign://签到
                startActivity(new Intent(getActivity(), SignActivity.class));
                break;
            case R.id.iv_head://头像
                startActivity(new Intent(getActivity(), MyInfoActivity.class));
                break;
            case R.id.tv_pwd://修改密码
                startActivity(new Intent(getActivity(), ModifyPwdActivity.class));
                break;
            case R.id.tv_draft://我的草稿箱
                startActivity(new Intent(getActivity(), MyDraftActivity.class));
                break;
            case R.id.tv_report://我的上报
                startActivity(new Intent(getActivity(), MyReportsActivity.class));
                break;
            //case R.id.tv_message://我的消息
            case R.id.message_layout:
                startActivity(new Intent(getActivity(), MyMessageActivity.class));
                break;
            case R.id.tv_partake://我的参与
                startActivity(new Intent(getActivity(), MyParticipationActivity.class));
                break;
            case R.id.tv_follow://我的关注
                startActivity(new Intent(getActivity(), MyFollowsActivity.class));
                break;
            case R.id.tv_exchange://积分兑换
                startActivity(new Intent(getActivity(), MyExchangeActivity.class));
                break;
            case R.id.tv_public://公众号
                startActivity(new Intent(getActivity(), MyPublicActivity.class));
//                startActivity(new Intent(getActivity(), SignActivity.class));

                break;
            case R.id.tv_advise://我的建议
//                startActivity(new Intent(getActivity(), MyAdviseActivity.class));
                startActivity(new Intent(getActivity(), FeedbackActivity.class));
                break;
            case R.id.tv_setting://设置
                startActivity(new Intent(getActivity(), MySettingActivity.class));
                break;
            case R.id.tv_logout://退出登录
                recordLogout();
                logout();
                break;
            default:
                break;
        }

    }

    private void recordLogout() {
        EasyHttp.post(ApiManager.URL_LOGOUT)
                .execute(new SimpleCallBack<List<ApiResult>>() {
                    @Override
                    public void onError(ApiException e) {
                        ToastUtils.showShort(e.getMessage());
                    }

                    @Override
                    public void onSuccess(List<ApiResult> result) {
                    }
                });
    }

    private void logout() {
        Intent intent = new Intent(getActivity(), LoginActivity.class);
        intent.putExtra(LoginActivity.EXTRA_LOGINED_SHOW_PAGE, ConstantManager.MAIN_PAGE_INDEX);
        startActivity(intent);
        if (account == null) {
            account = App.getInstance().getCurrentAccount();
        }
        account.setPassword("");
        account.setToken("");
        account.setLoginStatus(ConstantManager.LOGIN_OUT);
//        清空cookie
        CookieManger cookieManger = EasyHttp.getCookieJar();
        cookieManger.removeAll();
        App.getInstance().updateAccount(account);
        App.getInstance().finishAllActivity();//关闭所有Activity
    }

    @Subscriber
    private void updateUser(GetUserEvent event) {
        presenter.getUserInfo();
    }

    @Override
    public void getUserInfo(UserInfoBean.UserInfoBeanObj accountObj) {
        if (accountObj != null) {
            tv_name.setText(accountObj.getName());
            tv_point.setText("积分  " + accountObj.getScore());
            CommonUtils.setUserAvatar(getActivity(), iv_head, accountObj.getAvatarId());
            account.setLev(StringUtils.isEmpty(accountObj.getLev()) ? "" : accountObj.getLev());
            account.setIdc(StringUtils.isEmpty(accountObj.getIdc()) ? "" : accountObj.getIdc());
            account.setName(StringUtils.isEmpty(accountObj.getName()) ? "" : accountObj.getName());
            account.setNickName(StringUtils.isEmpty(accountObj.getNickName()) ? "" : accountObj.getNickName());
            account.setAvatarId(accountObj.getAvatarId());
            account.setSex(accountObj.getSex());
            account.setScore(StringUtils.isEmpty(accountObj.getScore()) ? "" : accountObj.getScore());
            account.setAddress(accountObj.getAddress());
            App.getInstance().updateAccount(account);
        }
    }

    @Subscriber
    private void loadUserInfo(LoadUserInfoEvent event) {
        account = App.getInstance().getCurrentAccount();
        setUserInfo();
    }

    @Override
    public void setUserInfoSuc(String msg) {

    }

    @Override
    public void setUserInfoFail(String msg) {

    }

}